package com.shangqing.document_management.util;

import com.shangqing.document_management.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 过滤器
 */
@Slf4j
public class ResFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest=(HttpServletRequest)servletRequest;
        HttpSession httpSession=httpServletRequest.getSession();
        if(httpSession==null){
            log.info("进入过滤器，未拿到用户");
            MDC.put("userName",null);
        }else{
            User user=(User)httpSession.getAttribute("user");
            if(user==null){
                log.info("进入过滤器，用户未null");
                MDC.put("userName",null);
            }else{
                log.info("进入过滤器===拿到用户"+user.getUsername());
                MDC.put("userId",String.valueOf(user.getId()));
                MDC.put("userName",user.getUsername());
            }
        }

        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {

    }
}
